﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Threading;
using HandyControl.Controls;
using IotClient.Entity;
using IotClient.Unity;
using MQTTnet;
using MQTTnet.Client;

namespace IotClient.VM
{
    public class MainVM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        public ClientSetting Setting
        {
            get => MQTTUnity.Setting;
            set => MQTTUnity.Setting = value;
        }
        public MQTTUnity MQTTUnity { get; set; } = new MQTTUnity();
        public Action<string, bool> LogCall
        {
            get => MQTTUnity.LogCall;
            set => MQTTUnity.LogCall = value;
        }

        public MainVM()
        {
            Setting.ConnentCall = MQTTUnity.ConnentCall;
            InitColck();
        }

        private DispatcherTimer timer;

        private void InitColck()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(3); // 设置时间间隔为3秒
            timer.Tick += Timer_Tick; // 绑定Tick事件
            timer.Start();
        }

        private void Timer_Tick(object? sender, EventArgs e)
        {
            if (Setting.Task == false)
            {
                return;
            }
            var data = MQTTUnity.AutoPayload();
            try
            {
                if (MQTTUnity.Push(data))
                {
                    LogCall($"发送成功：{data}", true);
                }
            }
            catch (Exception ex)
            {
                LogCall($"Err:" + ex.Message, true);
            }
        }
    }
}
